package com.central.oauth.mobile;

import com.central.oauth.service.IValidateCodeService;
import com.central.oauth.service.MyUserDetailsService;
import com.central.oauth2.common.token.MobileCodeAuthenticationToken;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 手机号+密码的验证方式，
 * 可以稍微修改下，com.central.oauth.mobile.MobileAuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
 * 进行短信验证码认证，就是 手机+验证码
 */
@Slf4j
@Setter
public class MobileCodeAuthenticationProvider implements AuthenticationProvider {

    private MyUserDetailsService userDetailsService;
    private IValidateCodeService validateCodeService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        MobileCodeAuthenticationToken authenticationToken = (MobileCodeAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String validCode = (String) authenticationToken.getCredentials();
        log.info("认证手机号>>{}", mobile);
        UserDetails user = userDetailsService.loadUserByMobile(mobile);
        if (user == null) {
            throw new InternalAuthenticationServiceException("手机号或验证码错误");
        }
        // 验证短信验证码是否正确
        log.info("验证手机号+验证码是否正确");
        validateCodeService.validate(mobile, validCode);
        MobileCodeAuthenticationToken authenticationResult = new MobileCodeAuthenticationToken(user, validCode,
                user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        // 返回认证结果信息
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
